<?php
/**
 * Description: 词语搭配作业模块
 * User: devforma
 * Date: 16/7/29
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class CiyudapeiModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 43;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目信息
        $qids = implode(',', $this->questionIds);
        $sql  = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$qids}) ORDER BY FIELD (`id`, {$qids})";
        $questions = $cmsdb->getResults($sql);

        $data = [];
        foreach ($questions as $question) {
            $data[] = [
                'question_id' => (int)$question->id,
                'question'    => $question->content,
                'options'     => explode('#', $question->options),
                'answer'      => $question->right_answer
            ];
        }

        $this->data['question'] = $data;
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_user_primary_question` WHERE `exercise_id`=:eid AND `user_id`=:uid';
        $records = $uddb->getResults($sql, [':eid' => $this->exerciseId, ':uid' => $this->userId]);
        $answers = [];
        foreach ($records as $r) {
            $answers[$r->question_id] = [
                'is_right' => (bool)$r->is_right,
                'answer'   => $r->user_answer
            ];
        }

        //合并用户答案
        foreach ($this->data['question'] as &$question) {
            $question['user_answer'] = $answers[$question['question_id']];
        }
    }

    /**
     * 设置作业的统计信息
     */
    protected function setSummary() {
        $this->data['summary'] = json_decode($this->userExerciseRecord->summary);
    }


    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && !empty($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answers = json_decode($this->submitArgs['answer_content']);

        $total = $right = 0;   //题目总数和答对数
        foreach ($answers as $q) {
            if ($q->is_right)
                $right++;

            $total++;

            //构造数据结构
            $questionRecord = [
                'question_id' => $q->question_id,
                'exercise_id' => $this->exerciseId,
                'user_id'     => $this->userId,
                'acting_time' => $this->now,
                'user_answer' => $q->answer,
                'is_right'    => $q->is_right,
                'status'      => 1
            ];

            $uddb->insert('history_user_primary_question', $questionRecord);
        }

        //更新已做人数
        $this->updateXingcePersonsNum();

        //保存统计信息
        $this->submitExerciseRecord['summary'] = json_encode([
            'position'     => $this->getXingcePersonsNum(),
            'duration'     => (int)$this->submitArgs['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($this->submitArgs['duration']/$total)
        ]);
    }
}